import { eventHandler, readBody, getMethod, getQuery, createError } from "h3";
import { ProductsStore } from "../../utils/products-store";

export default eventHandler(async (event) => {
  const method = getMethod(event);

  // GET /api/products - 获取商品列表
  if (method === "GET") {
    const query = getQuery(event);
    const { page = 1, limit = 10, category, search } = query;

    let filteredProducts = ProductsStore.getAll();

    // 根据分类过滤
    if (category) {
      filteredProducts = ProductsStore.getByCategory(category.toString());
    }

    // 根据搜索关键词过滤
    if (search) {
      filteredProducts = ProductsStore.search(search.toString());
    }

    // 分页
    const pageNum = parseInt((page || 1).toString());
    const limitNum = parseInt((limit || 10).toString());
    const startIndex = (pageNum - 1) * limitNum;
    const endIndex = startIndex + limitNum;
    const paginatedProducts = filteredProducts.slice(startIndex, endIndex);

    return {
      success: true,
      data: paginatedProducts,
      pagination: {
        page: pageNum,
        limit: limitNum,
        total: filteredProducts.length,
        totalPages: Math.ceil(filteredProducts.length / limitNum),
      },
    };
  }

  // POST /api/products - 创建新商品
  if (method === "POST") {
    const body = await readBody(event);

    // 验证必填字段
    if (!body.name || !body.price) {
      throw createError({
        statusCode: 400,
        statusMessage: "商品名称和价格是必填字段",
      });
    }

    const newProduct = ProductsStore.create({
      name: body.name,
      price: Number(body.price),
      description: body.description || "",
      category: body.category || "未分类",
      stock: Number(body.stock) || 0,
    });

    return {
      success: true,
      data: newProduct,
      message: "商品创建成功",
    };
  }

  // 不支持的HTTP方法
  throw createError({
    statusCode: 405,
    statusMessage: "Method Not Allowed",
  });
});
